<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2018/12/6
 * Time: 9:08
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Mall;

class MallController extends Controller
{

    /**
     * 获取商品列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(){
        $params = [
            'name' => (string)request('name',''),
        ];
        $list = Mall::select('id','name','prices','score','number','thumb','status','changed','sort','created_at','updated_at','intro','details')
            ->where(function($query) use($params){
                if ($params['name']){
                    $query->where('name','like','%'.$params['name'].'%');
                }
            })
            ->orderBy('id','DESC')
            ->orderBy('sort','DESC')
            ->paginate(20);
        $this->stateToText($list,[
            'status' => Mall::STATUS_TEXT,
            'sort'=> Mall::SORT_TEXT,
        ]);
        return $this->returnJson(0,'',$list);
    }

    /**
     * 获取商品详情
     * @return \Illuminate\Http\JsonResponse
     */
//    public function info(){
//        $id = (int)request('id',0);
//        $info = Mall::find($id);
//        if($info){
//            return $this->returnJson(0,'',$info);
//        }
//        return $this->returnJson(1,'error');
//    }


    //商品信息更新
    public function update(){
        $data = request()->all();

        if(!isset($data['id'])){
            $data['id'] = 0;
        }

        if ($data['id'] > 0){
            //编辑
            $info = Mall::find($data['id']);
            if(!$info){
                return $this->returnJson(1, '数据不存在');
            }
            $info->update($data);
            return $this->returnJson(0, '编辑商品信息成功');
        }else {
            //新增
            unset($data['id']);
            Mall::create($data);
            return $this->returnJson(0,'新增商品信息成功');
        }
    }

    /**
     * 商品删除
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function destroy(){
        try {
            $id = (int)request('id',0);
            Mall::destroy($id);
            return $this->returnJson(0);
        } catch (\Exception $e) {
            return $this->returnJson(1, '删除失败');
        }
    }

    /**
     * 商品批量删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroyAll(){
        $lists = request('data','');
        if($lists){
            try {
                Mall::destroy($lists);
                return $this->returnJson(0);
            } catch (\Exception $e) {
                return $this->returnJson(1, '批量删除失败');
            }
        }
        return $this->returnJson(1, '批量删除失败');
    }

}